package com.itheima.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter("/*")
public class LoginCheckFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        Long employee = (Long) request.getSession().getAttribute("employee");
        Long user = (Long) request.getSession().getAttribute("user");
        String[] url = new String[]{
                "/backend/**",
                "/front/**",
                "/employee/login",
                "/employee/logout",
                "/user/login",
                "/user/sendMsg"
        };
        String requestURI = request.getRequestURI();
        boolean check = check(url, requestURI);
        if (check) {
            chain.doFilter(request, response);
            return;
        }
        if (employee != null) {
            BaseContext.setCurrentId(employee);
            chain.doFilter(request, response);
            return;
        }
        if (user != null) {
            BaseContext.setCurrentId(user);
            chain.doFilter(request, response);
            return;
        }
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
    }

    //路径匹配器
    public static final AntPathMatcher antPathMatcher = new AntPathMatcher();

    private boolean check(String[] url, String requestURI) {
        for (String s : url) {
            boolean match = antPathMatcher.match(s, requestURI);
            if (match) {
                return true;
            }
        }
        return false;
    }
}
